﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.Communication;
using Sharp.Platform.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter.Areas.Platform.Models;

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    public class PermissionController : Controller
    {
        // GET: Platform/Permission
        public ActionResult Index()
        {
            IEnumerable<PermissionDTO> list;
            using (var proxy = new ServiceProxy<IUserService>())
            {
                list = proxy.Channel.AllPermissions();

                var newList = new List<PermissionIndexViewModel>();
                Build(list, newList, null);
                return View(newList);
            } 
        }
        private void Build(IEnumerable<PermissionDTO> table, List<PermissionIndexViewModel> node, Guid? parentValue)
        {
            var rows = table.Where(x => x.ParentId == parentValue).OrderBy(x => x.OrderIndex);
            foreach (var row in rows)
            {
                var _node = new PermissionIndexViewModel();
                _node.Title = row.Title;
                _node.Id = row.Id;
                _node.ParentId = row.ParentId;
                if (row.ParentId == null)
                {
                    _node.Itemclass = string.Format("treegrid-{0}", row.Id);
                }
                else
                {
                    _node.Itemclass = string.Format("treegrid-{0} treegrid-parent-{1}", row.Id, row.ParentId);
                }


                node.Add(_node);

                Build(table, node, row.Id);
            }
        }

        public ActionResult Scan()
        {
            var scan = new PermissionScan();
            var list = scan.GetAllActionByAssembly();
            using (var proxy = new ServiceProxy<IUserService>())
            {
                proxy.Channel.UpdatePermission(list);
            }

            return null;
        }
    }
}